<template>
  <xr-create :loading="loading" :title="title" @close="close" @save="saveClick">
    <create-sections title="基本信息">
      <wk-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            :requestShow="requestShow"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <create-sections title="联系信息">
      <wk-form
        ref="crmForm1"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList1"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <create-sections title="学员状态">
      <wk-form
        ref="crmForm2"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList2"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <create-sections title="籍贯">
      <wk-form
        ref="crmForm3"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList3"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <create-sections title="设计类">
      <wk-form
        ref="crmForm4"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList5"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <create-sections title="系统信息">
      <wk-form
        ref="crmForm5"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList4"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="data.disabled"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from "@/api/crm/common";
import { crmContactsSaveAPI } from "@/api/crm/contacts";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";
import { CrmRelativeCell } from "@/components/CreateCom";

import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { isEmpty } from "@/utils/types";
import { TimeSelect } from "element-ui";

export default {
  // 新建编辑
  name: "ContactsCreate",

  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    WkForm,
  },

  mixins: [CustomFieldsMixin],

  props: {
    phone: String,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
  },

  data() {
    return {
      loading: false,
      requestShow: true,
      baseFields: [],
      fieldList: [],
      fieldList1: [],
      fieldList2: [],
      fieldList3: [],
      fieldList4: [],
      fieldList5: [],
      fieldList6: [],
      fieldForm: {},
      fieldRules: {},
      itemCover: null,
    };
  },

  computed: {
    title() {
      return this.action.type === "update" ? "编辑联系人" : "新建联系人";
    },
  },

  watch: {},

  created() {
    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true;
      const params = {
        label: crmTypeModel.contacts,
      };

      if (this.action.type == "update") {
        params.id = this.action.id;
      }

      filedGetFieldAPI(params)
        .then((res) => {
          const list = res.data || [];
          if (!isEmpty(this.phone)) {
            list.forEach((item) => {
              if (item.formType === "mobile") {
                item.defaultValue = this.phone;
              }
            });
          }
          const fieldList = [];

          const fieldList1 = [];
          const fieldList2 = [];
          const fieldList3 = [];
          const fieldList4 = [];
          const fieldList5 = [];
          const fieldRules = {};
          const fieldForm = {};
          list.forEach((item) => {
            const temp = {};
            temp.field = item.fieldName;
            temp.formType = item.formType;
            temp.fieldId = item.fieldId;
            // console.log(temp);
            temp.inputTips = item.inputTips;
            temp.name = item.name;
            temp.setting = item.setting;

            // console.log(item);
            if (item.fieldName === "telephone") {
              temp.maxlength = item.maxLength;
            } else if (item.fieldName === "trainingPeriods") {
              temp.maxlength = item.maxLength;
            } else if (item.fieldName === "turnEarlyNumber") {
              temp.maxlength = item.maxLength;
            } else if (item.fieldName === "relearnPeriods") {
              temp.maxlength = item.maxLength;
            } else if (item.fieldName === "vipPeriods") {
              temp.maxlength = item.maxLength;
            }

            const canEdit = this.getItemIsCanEdit(item, this.action.type);
            // 是否能编辑权限
            if (canEdit) {
              fieldRules[temp.field] = this.getRules(item);
            }

            // 是否可编辑
            temp.disabled = !canEdit;

            // 禁止某些业务组件选择
            if (temp.formType == "customer") {
              if (this.action.type == "relative") {
                const relativeDisInfos = {
                  customer: { customer: true },
                  business: { customer: true },
                  vipStudents: { customer: true },
                };

                // 在哪个类型下添加
                const relativeTypeDisInfos =
                  relativeDisInfos[this.action.crmType];
                if (relativeTypeDisInfos) {
                  // 包含的字段值
                  temp.disabled = relativeTypeDisInfos[item.formType] || false;
                }
              }
            }

            // 特殊字段允许多选
            this.getItemRadio(item, temp);

            // 获取默认值
            fieldForm[temp.field] = this.getItemValue(
              item,
              this.action.data,
              this.action.type
            );
            if (
              item.fieldId == 1101847 ||
              item.fieldId == 1101848 ||
              item.fieldId == 1101857 ||
              item.fieldId == 1101964
            ) {
              fieldList.push(temp);
            } else if (
              item.fieldId == 1101850 ||
              item.fieldId == 1101992 ||
              item.fieldId == 1101993 ||
              item.fieldId == 1101994 ||
              item.fieldId == 1101995
            ) {
              fieldList1.push(temp);
            } else if (
              item.fieldId == 1101996 ||
              item.fieldId == 1101997 ||
              item.fieldId == 1101998 ||
              item.fieldId == 1102022 ||
              item.fieldId == 1101999 ||
              item.fieldId == 1102000 ||
              item.fieldId == 1102001 ||
              item.fieldId == 1102101
            ) {
              //新建联系人 重修期数排序
              if (item.fieldId != 1102101) {
                fieldList2.push(temp);
                if (item.fieldId == 1102001) {
                  fieldList2.push(this.itemCover);
                }
              } else {
                this.itemCover = temp;
              }
            } else if (item.fieldId == null && item.fieldName == 'mapAddress') {
              fieldList3.push(temp);
            } else if (item.fieldId == 1101856) {
              fieldList4.push(temp);
            } else {
              fieldList5.push(temp);
            }
          });
          this.baseFields = list;
          this.fieldList = fieldList;
          this.fieldList1 = fieldList1;
          this.fieldList2 = fieldList2;
          this.fieldList3 = fieldList3;
          this.fieldList4 = fieldList4;
          this.fieldList5 = fieldList5;
          this.fieldForm = fieldForm;
          this.fieldRules = fieldRules;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 保存
     */
    saveClick() {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      // console.log(this.fieldForm);
      crmForm.validate((valid) => {
        if (valid) {
          const params = this.getSubmiteParams(this.baseFields, this.fieldForm);
          this.submiteParams(params);
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == "update") {
        params.entity.contactsId = this.action.id;
        params.entity.batchId = this.action.batchId;
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }
      crmContactsSaveAPI(params)
        .then((res) => {
          this.loading = false;

          this.$message.success(
            this.action.type == "update" ? "编辑成功" : "添加成功"
          );

          this.close();

          // 保存成功
          this.$emit("save-success", {
            type: "contacts",
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    formChange(item, index, value, valueList, value2) {
      
      //新建联系人中 休学和重修的选项取反
      //休学选项为'是'的时候
      if (item.fieldId == 1102022 && value == "是") {
        //重修为 否
        this.fieldForm.relearn = "否";
      }
      //重修为'是'时
      if (item.fieldId == 1102001 && value == "是") {
        //休学为'否'
        this.fieldForm.suspensionSchooling = "否";
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      this.fieldList1.forEach((fieldItem) => {
        if (fieldItem.fieldId == "1101994") {
          this.fieldForm.trainingPeriods =
            data.value.length > 0
              ? data.value[0].trainingPeriods
              : (this.fieldForm.trainingPeriods = "");
        } else if (fieldItem.fieldId == "1101850") {
          this.fieldForm.telephone =
            data.value.length > 0 ? data.value[0].telephone : "";
        } else if (fieldItem.fieldId == "1101993") {
          this.fieldForm.qq = data.value.length > 0 ? data.value[0].qq : "";
        } else if (fieldItem.fieldId == "1101992") {
          this.fieldForm.wechat =
            data.value.length > 0 ? data.value[0].wechat : "";
        }
      });
      // console.log(fieldItem);
      this.$set(this.fieldForm, field.field, data.value);
      this.$refs.crmForm.instance.validateField(field.field);
    },

    /**
     * 关闭
     */
    close() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
